package com.benshou.bsoa.service.yida;

import com.aliyun.dingtalkyida_2_0.Client;
import com.aliyun.dingtalkyida_2_0.models.SaveFormDataHeaders;
import com.aliyun.dingtalkyida_2_0.models.SaveFormDataRequest;
import com.aliyun.dingtalkyida_2_0.models.SaveFormDataResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.benshou.bsoa.dto.yida.req.YiDaReq;
import com.benshou.bsoa.utils.CreateAccessTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * 宜搭相关表单实例创建
 * @auth hyh
 *  2025/04/28
 */
@Service
public class PostYiDaService {

    @Value("${yida_app_code}")
    private String APP_CODE;

    @Value("${yida_app_secret}")
    private String APP_SECRET;

    @Autowired
    private CreateAccessTokenUtil createAccessTokenUtil;


    /**
     * 保存表单实例到宜搭
     * @param yiDaReq 前端传递的参数
     * @return 表单保存的响应信息 SaveFormDataResponse
     * @throws Exception
     */
    public SaveFormDataResponse saveFormData(YiDaReq yiDaReq) throws Exception {
        // 创建 Client
        Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        Client client = new Client(config);

        // 准备 Headers
        SaveFormDataHeaders headers = new com.aliyun.dingtalkyida_2_0.models.SaveFormDataHeaders();
        headers.xAcsDingtalkAccessToken = createAccessTokenUtil.getToken();

        // 准备 Request
        SaveFormDataRequest request = new com.aliyun.dingtalkyida_2_0.models.SaveFormDataRequest()
                .setAppType(APP_CODE) // 宜搭类型中的应用类型
                .setSystemToken(APP_SECRET)  // 宜搭类型中的应用密钥
                .setUserId(yiDaReq.getUserId())
                .setLanguage("zh_CN")
                .setFormUuid(yiDaReq.getFormUuid())
                .setFormDataJson(yiDaReq.getFormDataJson())
                .setUseAlias(false);

        try {
            SaveFormDataResponse saveFormDataResponse = client.saveFormDataWithOptions(request, headers, new RuntimeOptions());
            return saveFormDataResponse;
        } catch (TeaException err) {
           throw new RuntimeException("Error occurred while saving form data: " + err.getMessage(), err);
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            throw new RuntimeException("Error occurred while saving form data: " + err.getMessage(), err);
        }
    }
}
